
import 'package:amway_superapp_creator_plugin/analysis/zhuge_goods_recommendation.dart';
import 'package:amway_superapp_creator_plugin/models/haowu_product_models.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';
import 'package:amway_superapp_creator_plugin/utils/log_util.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/view_state.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/base_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:uuid/uuid.dart';

import '../api.dart';

class RecommendProductVM extends BaseModel {
  RecommendProductVM({@required Api api}) {
    this.api = api;
  }

  List<HaowuContent> _contentList=[];
  List<HaowuContent> get contentList => _contentList;
  List<HaowuProduct> _officialProductList=[];
  List<HaowuProduct> get officialProductList => _officialProductList;
  set officialProductList(List<HaowuProduct> value) {
    _officialProductList = value;
  }
  HaowuData haowuData;
  List<HaowuContent> cachedContents;
  String ada="ada";
  String amwayId="123";
  ScrollController _controller;
  ///删除的列表
  List<dynamic> removedList=[];
  ///更改排序的列表
  Map<String,int> orderMap=Map();
  ///官方列表折叠
  bool _isFolded=false;
  bool get isFolded => _isFolded;
  set isFolded(bool value) {
    _isFolded = value;
    notifyListeners();
  }

  bool _isLoading=false;


  bool get isLoading => _isLoading;

  double productHeight=ScreenUtil().setHeight(344);
  double recommendHeight=ScreenUtil().setHeight(147);

  void reorderProductList(Key from, Key to) {
    int indexFrom=-1;
    int indexTo=-1;
    for(int i=0;i<contentList.length;i++){
      if (ValueKey(contentList.elementAt(i).product.skuCode)==from) {
        indexFrom=i;
      }else if(ValueKey(contentList.elementAt(i).product.skuCode)==to){
        indexTo=i;
      }
      if(indexFrom!=-1&&indexTo!=-1){
        break;
      }
    }

    int fromNo=contentList[indexFrom].no;
    int toNo=contentList[indexTo].no;

    if(contentList[indexFrom].id!=null){
      orderMap[contentList[indexFrom].id.toString()]=toNo;
    }else{
      orderMap[contentList[indexFrom].sortId]=toNo;
    }

    if(contentList[indexTo].id!=null){
      orderMap[contentList[indexTo].id.toString()]=fromNo;
    }else{
      orderMap[contentList[indexTo].sortId]=fromNo;
    }


    final draggedItem = contentList[indexFrom];
    contentList.removeAt(indexFrom);
    contentList.insert(indexTo, draggedItem);
    notifyListeners();
  }

  void switchRecommendListState() {
    isFolded=!isFolded;
    notifyListeners();
  }





  void fetchList(String ada, amwayId) async{
    ///
    /// 官方和自定义列表分开请求
    this.ada=ada;
    setState(ViewState.Busy);
    api.getHaowuProductModels((json) {
      setState(ViewState.Idle);
      try {
        haowuData = HaowuData.fromJson(json);
        cachedContents=haowuData.content;
        api.getHaowuOfficialList(ada,(data) {
          List<dynamic> list = data;
          List<HaowuProduct> productList=[];
          list.forEach((element) { 
            productList.add(HaowuProduct.fromJson(element));
          });
          preProcessContent(cachedContents,productList);
          notifyListeners();
        }, (data) {
          setState(ViewState.Idle);
          preProcessContent(cachedContents,null);
          ToastUtils.showShortToast(data.toString());
          notifyListeners();
        });

      } on Exception catch (e) {
        // 任意一个异常
        ToastUtils.showShortToast(e.toString());
      } catch (e) {
        // 非具体类型
        ToastUtils.showShortToast(e.toString());
      }
    }, (json) {
      setState(ViewState.Idle);
      ToastUtils.showShortToast('服务器异常');
      LogUtil.e(json);
    }, ada);
  }

  void dataReport(List<HaowuContent> contents){
    int state=1;
    if(contents.isEmpty){
      state=0;
    }else{
      for(int i=0;i<contentList.length;i++){
        if((contentList[i].displayAudits != null &&
            contentList[i].displayAudits[0] != null &&
            contentList[i].displayAudits[0].status == 'UN_PASS')){
          state=2;
          break;
        }
      }
    }
    ZhugeGoodsRecommendationAnalysis.goodsReCommendaionPageLoadFinsh(state);
  }

  void preProcessContent(List<HaowuContent> contents, List<HaowuProduct> productList){

    dataReport(contents);

    // contents.sort((a,b)=>a.no.compareTo(b.no));
    contents.forEach((content) {
      if(content.officialFlag=="NO"&&content.sortId==null){
        var uuid = Uuid().v1();
        content.sortId=uuid;
      }
      if(content.product.picture!=null&&!content.product.picture.startsWith('http')){
        content.product.picture=OssHelper.pictureBaseUrl+content.product.picture;
      }
      contentList.add(content);
    });
    if(productList!=null&&productList.isNotEmpty){
      officialProductList.addAll(productList);
      officialProductList.forEach((oProduct) {
        contents.forEach((content) {
          if(oProduct.skuCode==content.product.skuCode){
            oProduct.isHidden=true;
          }
        });
        if(oProduct.picture!=null&&!oProduct.picture.startsWith('http')){
          oProduct.picture=OssHelper.pictureBaseUrl+oProduct.picture;
        }
      });
    }
  }

  void showContentLengthError(HaowuContent data, bool bool) {
    data.showLengthExceededWarning=bool;
    notifyListeners();
  }

  bool checkAnyItemsEdited(){
    bool edited=false;
    if(removedList!=null&&removedList.isNotEmpty){
     edited=true;
    }
    if(orderMap.isNotEmpty){
      edited=true;
    }
    if(contentList!=null&&contentList.isNotEmpty){
      if(contentList.length!=cachedContents.length){
        edited=true;
      }
      contentList.forEach((element) {
        if(element.isEdited){
          edited=true;
        }
      });
    }
    return edited;
  }

  bool validateContents(ScrollController controller){
    bool isValid=true;
    int notifyType=-1;
    int notifyIndex=-1;
    if(!checkAnyItemsEdited()){
      notifyType=0;
      isValid=false;
    }else{
      for(int i=0;i<contentList.length;i++){
        if(contentList.isEmpty){
          isValid=true;
          break;
        }else if(contentList[i].description==null||contentList[i].description.trim().isEmpty){
          contentList[i].showEmptyNotification=true;
          contentList[i].isEdited=false;
          notifyType=1;
          if(notifyIndex==-1){
            notifyIndex=i;
          }
          isValid=false;
          notifyListeners();
          break;
        }else if(contentList[i].description!=null&&(contentList[i].showLengthExceededWarning||contentList[i].description.trim().length>70)){
          contentList[i].showLengthExceededWarning=true;
          contentList[i].isEdited=false;
          notifyType=3;
          if(notifyIndex==-1){
            notifyIndex=i;
          }
          isValid=false;
          break;
        }else if(!contentList[i].isEdited
            &&contentList[i].displayAudits!=null
            &&contentList[i].displayAudits[0].status!=null
            &&contentList[i].displayAudits[0].status=='UN_PASS'){
          isValid=false;
          notifyType=2;
          contentList[i].isEdited=false;
          if(notifyIndex==-1){
            notifyIndex=i;
          }
          notifyListeners();
          break;
        }
      }
    }

    if(notifyIndex!=-1&&controller!=null){
      controller.animateTo(ScreenUtil().setHeight(160)+notifyIndex * productHeight, duration: Duration(seconds: 2), curve: Curves.fastOutSlowIn);
    }
    if(notifyType!=-1){
      switch(notifyType){
        case 0:
          ToastUtils.showLongToast('请做了任何更改再提交哦');
          break;
        case 1:
          ToastUtils.showLongToast('必须填写推荐语哦');
          break;
        case 2:
          ToastUtils.showLongToast('请修改审核未通过的选项');
          break;
        case 3:
          ToastUtils.showLongToast('请修改字数超过限制的选项');
      }
    }
    return isValid;
  }

  void modifyList(ScrollController controller,HttpSuccessCallback callback){
    if(!validateContents(controller)){
      return;
    }

    if(!_isLoading){
      _isLoading=true;
    }else{
      ToastUtils.showShortToast("请稍候");
      return;
    }




    if(contentList.isNotEmpty&&contentList.length>1){
      List<String> skuList=[];
      contentList.forEach((element) {
        skuList.add(element.product.skuCode);
      });
      ZhugeGoodsRecommendationAnalysis.goodsReCommendaionSaveGoods("好物推荐页", skuList);

      contentList[0].no=100;
      for(int i=1;i<contentList.length;i++){
        contentList[i].no=contentList[i-1].no*2;
      }
    }

    setState(ViewState.Busy);
    var map = <String, dynamic>{};
    map["ada"] = ada;
    map["amwayId"] = contentList.isNotEmpty?contentList[0].amwayId:amwayId;
    if (contentList != null) {
      map["payloadList"] = contentList;
    }
    map["removeIdList"]=removedList;
    map["sortIdNoMap"]=orderMap;

    api.modifyRecommendList(ada,map,(data){
      _isLoading=false;
      setState(ViewState.Idle);
      callback.call('success');
    },(data){
      _isLoading=false;
      setState(ViewState.Idle);
      ToastUtils.showShortToast('保存失败');
    });
  }

  void removeItem(HaowuContent data) {
    dynamic markId="";
    if(data.id!=null){
      markId=data.id;
      removedList.add(markId);
    }else if(data.sortId!=null){
      markId=data.sortId;
    }
    contentList.removeWhere((element) => (element.sortId==markId||element.id==markId));
    officialProductList.forEach((element) {
      if(element.skuCode==data.product.skuCode){
        element.isHidden=false;
      }
    });
    notifyListeners();
  }

  void addOfficial(HaowuProduct data) {
    if(contentList.length+1>50){
      ToastUtils.showLongToast("最多只能添加50个商品哦");
      return;
    }
    HaowuContent content=HaowuContent();
    content.product=data;
    content.sortId=Uuid().v1();
    content.officialFlag='YES';
    int max=1;
    contentList.forEach((element) {
      if(element.no>max){
        max=element.no;
      }
    });
    content.no=max+1;
    content.ada=ada;
    content.amwayId=(contentList.isNotEmpty&&contentList[0]!=null)?contentList[0].amwayId:amwayId;
    contentList.insert(0, content);
    // contentList.add(content);

    officialProductList.forEach((element) {
      if(data.skuCode==element.skuCode){
        element.isHidden=true;
      }
    });
    notifyListeners();
    if(_controller!=null){
      _controller.animateTo(0, duration: Duration(milliseconds: 500), curve: Curves.fastOutSlowIn);
    }
  }

  void addCustom(List<HaowuProduct> beans) {
    beans.forEach((bean) {
      bool repeated=false;
      HaowuContent content=HaowuContent();
      content.ada=ada;
      content.amwayId=(contentList.isNotEmpty&&contentList[0]!=null)?contentList[0].amwayId:amwayId;
      int max=1;
      contentList.forEach((element) {
        if(element.no>max){
          max=element.no;
        }
        if(bean.skuCode==element.product.skuCode){
          repeated=true;
        }
      });
      content.no=max+1;
      content.officialFlag='NO';
      content.sortId=Uuid().v1();
      if (bean.picture != null && !bean.picture.startsWith('http')) {
        bean.picture = OssHelper.pictureBaseUrl + bean.picture;
      }
      content.product=bean;
      content.description='';

      // contentList.add(content);
      if(!repeated){
        if(contentList.length+1>50){
          ToastUtils.showLongToast("最多只能添加50个商品哦");
          return;
        }
        contentList.insert(0, content);
      }
    });
    notifyListeners();
  }

  void setScrollController(ScrollController controller) {
    _controller=controller;
  }
}


